package com.cloud.wms.ui.sort.fragment;

import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.tools.PlayVoiceManager;
import com.cloud.core.utils.NumberUtils;
import com.cloud.core.utils.VoiceSourceUtils;
import com.cloud.core.widget.decoration.GridItemDecoration;
import com.cloud.widget.ScanText;
import com.cloud.widget.utils.DensityUtils;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseViewPagerFragment;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.ui.sort.contract.CarSortDetachContract;
import com.cloud.wms.ui.sort.entity.SortCommodityEntity;
import com.cloud.wms.ui.sort.presenter.CarSortDetachPresenter;
import com.cloud.wms.widget.dialog.TaskCompleteDialog;
import com.trello.rxlifecycle3.LifecycleTransformer;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author:Chen
 * @Date: 2021-03-07 16:10
 * @Description:
 */
public class CarSortDetachFragment extends BaseViewPagerFragment<CarSortDetachPresenter> implements CarSortDetachContract.View {
    @BindView(R.id.scan_text)
    ScanText scanText;
    @BindView(R.id.tv_scan_code)
    TextView tvScanCode;
    @BindView(R.id.tv_scan_name)
    TextView tvScanName;
    @BindView(R.id.tv_pos_setting)
    TextView tvPosSetting;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.ll_pos_content)
    LinearLayout llPosContent;
    @BindView(R.id.tv_commodity_name)
    TextView tvCommodityName;
    @BindView(R.id.tv_pos_code)
    TextView tvPosCode;
    @BindView(R.id.tv_commodity_amount)
    TextView tvCommodityAmount;
    @BindView(R.id.ll_commodity_content)
    LinearLayout llCommodityContent;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.ll_btn)
    LinearLayout llBtn;
    @BindView(R.id.rv_container_list)
    RecyclerView rvContainerList;
    private long batchId;
    private TaskEntity taskEntity;
    private ArrayList<SortCommodityEntity> commodityList;
    private int index = 0;
    private BaseQuickAdapter<SortCommodityEntity, BaseViewHolder> mAdapter;
    private BaseQuickAdapter<SortCommodityEntity.OrderBoxBean, BaseViewHolder> mContainerAdapter;

    @Override
    protected int getResId() {
        return R.layout.fragment_sort_car_detach;
    }

    @Override
    protected void setupComponent() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void initEvent(Bundle bundle) {
        batchId = getArguments().getLong("BatchId");
        taskEntity = getArguments().getParcelable("Task");

        rvList.setLayoutManager(new GridLayoutManager(getContext(), 3));
        mAdapter = new BaseQuickAdapter<SortCommodityEntity, BaseViewHolder>(R.layout.item_group_sort_pos) {
            @Override
            protected void convert(BaseViewHolder helper, SortCommodityEntity item) {
                helper.setText(R.id.tv_pos_code, item.getPosCode())
                        .setVisible(R.id.label_view, item.isFlag());
            }
        };
        rvList.setItemAnimator(new DefaultItemAnimator());
        rvList.addItemDecoration(GridItemDecoration.newBuilder().spanCount(3)
                .verticalDivider(ContextCompat.getDrawable(getContext(), R.color.bg_base_content), DensityUtils.Dp2Px(getContext(), 6), false)
                .horizontalDivider(ContextCompat.getDrawable(getContext(), R.color.bg_base_content), DensityUtils.Dp2Px(getContext(), 6), false)
                .build());
        rvList.setAdapter(mAdapter);

        rvContainerList.setLayoutManager(new GridLayoutManager(getContext(), 3));
        mContainerAdapter = new BaseQuickAdapter<SortCommodityEntity.OrderBoxBean, BaseViewHolder>(R.layout.item_sort_detach_confirm) {
            @Override
            protected void convert(BaseViewHolder helper, SortCommodityEntity.OrderBoxBean item) {
                helper.setText(R.id.tv_container_num, item.getBindNum() + "号")
                        .setText(R.id.tv_commodity_amount, item.getNeedAmount() + "")
                        .setText(R.id.tv_container_code, item.getContainerCode());
            }
        };
        rvContainerList.setItemAnimator(new DefaultItemAnimator());
        rvContainerList.addItemDecoration(GridItemDecoration.newBuilder().spanCount(3)
                .verticalDivider(ContextCompat.getDrawable(getContext(), R.color.bg_base_content), DensityUtils.Dp2Px(getContext(), 6), false)
                .horizontalDivider(ContextCompat.getDrawable(getContext(), R.color.bg_base_content), DensityUtils.Dp2Px(getContext(), 6), false)
                .build());
        rvContainerList.setAdapter(mContainerAdapter);

        mPresenter.loadSortCommodity(batchId);
    }

    @Override
    public ScanText getScanText() {
        return scanText;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onScanHandle(String result, int resultCode) {
        super.onScanHandle(result, resultCode);
        scanText.addHistory(result);
        SortCommodityEntity commodityEntity = commodityList.get(index);
        if (llPosContent.getVisibility() == View.VISIBLE) {
            if (result.equalsIgnoreCase(commodityEntity.getPosCode())) {
                success("库位扫描验证成功，请扫描商品！");
                llPosContent.setVisibility(View.GONE);
                llCommodityContent.setVisibility(View.VISIBLE);
                llBtn.setVisibility(View.VISIBLE);
                tvScanCode.setText(commodityEntity.getBarCode());
                tvScanName.setText("商品条码");
                scanText.setHint("商品条码");
            } else {
                info("库位扫描验证失败！");
            }
        } else {
            if (commodityEntity.matchBarCode(result)) {
                success("条码扫描验证成功，请确认数量！");
                for (int i = 0; i < commodityEntity.getOrderBoxBeans().size(); i++) {
                    String bindNum = commodityEntity.getOrderBoxBeans().get(i).getBindNum();
                    Integer[] numVoice = VoiceSourceUtils.formatNumVoice(NumberUtils.getIntegerValue(bindNum));
                    scanVoice(numVoice);
                }
                btnSubmit.setEnabled(true);
            } else {
                info("条码扫描验证失败！");
            }
        }
    }

    @Override
    public void onSuccess(Message message) {
        switch (message.what) {
            case CarSortDetachPresenter.SORT_COMMODITY:
                commodityList = ((ArrayList<SortCommodityEntity>) message.obj);
                setDataToView(commodityList.get(index = 0));
                break;
            case CarSortDetachPresenter.SORT_POS_DETAIL:
                ArrayList<SortCommodityEntity> entities = (ArrayList<SortCommodityEntity>) message.obj;
                mAdapter.setNewInstance(entities);
                break;
            case CarSortDetachPresenter.SUBMIT_SORT:
                if (index < commodityList.size() - 1) {
                    success("分拣成功，请继续分拣当前库位另一商品！");
                    index++;
                    SortCommodityEntity commodityEntity = commodityList.get(index);
                    setDataToView(commodityEntity);
                    llPosContent.setVisibility(View.GONE);
                    llCommodityContent.setVisibility(View.VISIBLE);
                    llBtn.setVisibility(View.VISIBLE);
                    tvScanCode.setText(commodityEntity.getBarCode());
                    tvScanName.setText("商品条码");
                    scanText.setHint("商品条码");
                } else {
                    success("分拣成功！");
                    mPresenter.loadSortCommodity(batchId);
                }
                break;
            case CarSortDetachPresenter.SORT_COMPLETE:
                success("分拣完成，请放置至指定地点！");
                new TaskCompleteDialog(getActivity()).show();
                break;
        }
    }

    private void setDataToView(SortCommodityEntity commodityBean) {
        llPosContent.setVisibility(View.VISIBLE);
        llCommodityContent.setVisibility(View.GONE);
        llBtn.setVisibility(View.GONE);
        btnSubmit.setEnabled(false);

        scanText.setHint("库位");
        tvScanCode.setText(commodityBean.getPosCode());
        tvScanName.setText("下架库位");
        tvCommodityName.setText(commodityBean.getCommodityName());
        tvPosCode.setText(commodityBean.getPosCode());
        tvCommodityAmount.setText(commodityBean.getNeedAmount() + "");


        mContainerAdapter.setNewInstance(commodityBean.getSortOrder());
    }

    @Override
    public <R> LifecycleTransformer<R> toLifecycle() {
        return bindToLifecycle();
    }

    public static BaseViewPagerFragment newInstance(Bundle bundle) {
        CarSortDetachFragment fragment = new CarSortDetachFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @OnClick({R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_submit:
                SortCommodityEntity commodityBean = commodityList.get(index);
                mPresenter.submitSort(taskEntity, commodityBean);
                break;
        }
    }
}
